//
//  NewsController.m
//  iCarStyle
//
//  Created by liunian on 13-9-10.
//  Copyright (c) 2013年 liunian. All rights reserved.
//

#import "NewsController.h"
#import "NewsEntity.h"
#import "ArticleCell.h"
#import "Article.h"
#import "ArticleManager.h"
#import "DataEnvironment.h"
#import "DetailViewController.h"
#import "TFHpple.h"
#import "SRRefreshView.h"

#define kSiteAPI    kNewsSiteAPI

#define kPushRefreshBodyColor  [UIColor colorWithRed:212.0/255.0 green:177.0/255.0 blue:138.0/255.0 alpha:1.0f]
#define kPushRefreshSkinColor  [UIColor clearColor]

@interface NewsController ()<ArticleManagerDelegate,SRRefreshDelegate>
@property (nonatomic, assign) id<NewsControllerDelegate>delegate;
@property (nonatomic, strong) NSArray *cNames;
@property (nonatomic, assign) BOOL      insertEnable;
@property (nonatomic, retain) SRRefreshView *headerCell;
@end

@implementation NewsController
@synthesize fetchedResultsController = _fetchedResultsController;

- (id)initWithStyle:(UITableViewStyle)style;
{
    self = [super initWithStyle:style];
    if (self) {
        // Custom initialization
        
        self.managedObjectContext = [[ArticleManager sharedManager] managedObjectContext];
    }
    return self;
}
- (NSString *)tabTitle
{
	return self.title;
}
- (NSString *)tabImageName
{
	return @"image-5";
}
- (id)initWithCatalog:(CatalogType)type delegate:(id<NewsControllerDelegate>)delegate{
    if (self = [self initWithStyle:UITableViewStylePlain]) {
        self.delegate = delegate;
        self.insertEnable = YES;
        self.title = @"知识";
        self.objectReq = [[ReqObject alloc] initWithCatalogType:type pageNum:1];
        [[ArticleManager sharedManager] addObserver:self];
        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(handleAppDidEnterBackground:)
                                                     name:UIApplicationDidEnterBackgroundNotification
                                                   object:nil];
        
        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(handleAppWillEnterForeground:)
                                                     name:UIApplicationWillEnterForegroundNotification
                                                   object:nil];
        
        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(handleAppWillBeginCache:)
                                                     name:UIApplicationhandleAppWillBeginCache
                                                   object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(handleAppDidEndCache:)
                                                     name:UIApplicationhandleAppDidEndCache
                                                   object:nil];
    }
    return self;
}
- (void)viewDidLoad
{
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor flatWhiteColor];
    self.navigationController.navigationBar.tintColor = [UIColor flatWhiteColor];
#if __IPHONE_OS_VERSION_MAX_ALLOWED < 70000
    
#else
    float systemName = [[[UIDevice currentDevice] systemVersion] floatValue];
    if(systemName >= 7.0)
    {
        self.edgesForExtendedLayout = UIRectEdgeAll;
//        self.extendedLayoutIncludesOpaqueBars = NO;
        self.modalPresentationCapturesStatusBarAppearance = NO;
        [self.navigationController.navigationBar setBarTintColor:[UIColor flatWhiteColor]];
        [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleDefault animated:YES];
        self.view.bounds = CGRectMake(0, -20, self.view.frame.size.width, self.view.frame.size.height);
    }
#endif
    _cNames = [NSArray arrayWithObjects:@"全部",@"美容知识",@"养护知识",@"维修知识",@"改装知识",@"车居知识",@"汽车用品",@"保险知识", nil];
    [NSFetchedResultsController deleteCacheWithName:@"Master"];
    NSError *error;
	if (![[self fetchedResultsController] performFetch:&error]) {
		// Update to handle the error appropriately.
		NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
		exit(-1);  // Fail
	}
    [self.tableView addSubview:self.headerCell];
}

- (void)didReceiveMemoryWarning{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (void)viewDidUnload {
    self.fetchedResultsController = nil;
}

- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [self.headerCell endRefresh];
}
#if __IPHONE_OS_VERSION_MAX_ALLOWED < 70000

#else
- (UIStatusBarStyle)preferredStatusBarStyle
{
    return UIStatusBarStyleLightContent;
}
#endif
- (void)viewWillReload{
    [self slimeRefreshStartRefresh:nil];
}

- (void)reload{
    if (self.objectReq.isLoading) {
        return;
    }
    [self.objectReq setIsLoading:YES];
    self.objectReq.pageNum = 1;
    [[ArticleManager sharedManager] reloadNewsWithReqObject:self.objectReq];
}

#pragma mark configure cell
- (void)configureCell:(ArticleCell *)cell atIndexPath:(NSIndexPath *)indexPath {
    NewsEntity *entity = [_fetchedResultsController objectAtIndexPath:indexPath];
    Article *article = [[ArticleManager sharedManager] makeArticleWithEntity:entity];
    [cell updateWithArticle:article];
}
#pragma mark SRRefreshDelegate
- (void)slimeRefreshStartRefresh:(SRRefreshView*)refreshView{
    [self reload];
}
#pragma mark ArticleManagerDelegate
- (void)mkManagerReloadDidFinishedWithReqObject:(ReqObject *)object{
    if (object.type != self.objectReq.type) {
        return;
    }
    BMLog(@"refreshed");
    [self.headerCell endRefresh];
    [self.objectReq setIsLoading:NO];
    [self.tableView reloadData];
}
#pragma mark - handle notifications
- (void)handleAppDidEnterBackground:(NSNotification *)notification {
    self.insertEnable = NO;
}

- (void)handleAppWillEnterForeground:(NSNotification *)notifcation {
    self.insertEnable = YES;
}

- (void)handleAppWillBeginCache:(NSNotification *)notifcation {
    self.insertEnable = NO;
}
- (void)handleAppDidEndCache:(NSNotification *)notifcation {
    self.insertEnable = YES;
}

#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    NSInteger count = [[self.fetchedResultsController sections] count];
	return count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    id <NSFetchedResultsSectionInfo> sectionInfo = [[self.fetchedResultsController sections] objectAtIndex:section];
	NSInteger count = [sectionInfo numberOfObjects];
	return count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    id  sectionInfo = [[self.fetchedResultsController sections] objectAtIndex:indexPath.section];
    if (indexPath.row == [sectionInfo numberOfObjects]){
        return 40;
    }
    return kHeightArticleCell;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    id  sectionInfo = [[self.fetchedResultsController sections] objectAtIndex:indexPath.section];
    if (indexPath.row < [sectionInfo numberOfObjects]) {
        static NSString *identifier = @"list";
        ArticleCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
        if (nil == cell) {
            cell = [[ArticleCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:identifier];
            [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
        }
        
        [self configureCell:cell atIndexPath:indexPath];
        return cell;
    }
    
    return nil;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    id  sectionInfo = [[_fetchedResultsController sections] objectAtIndex:indexPath.section];
    
    if (indexPath.row == [sectionInfo numberOfObjects]) {

    }
    if (indexPath.row < [sectionInfo numberOfObjects]) {
        NewsEntity *entity = [_fetchedResultsController objectAtIndexPath:indexPath];
        Article *article = [[ArticleManager sharedManager] makeArticleWithEntity:entity];
        DetailViewController *detailVC = [[DetailViewController alloc] initWithArticle:article];
        [[DataEnvironment sharedDataEnvironment].navController pushViewController:detailVC animated:YES];
    }
}

#pragma mark - UIScrollViewDelegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    [_headerCell scrollViewDidScroll];
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
    [_headerCell scrollViewDidEndDraging];
}
#pragma mark NSFetchedResultsControllerDelegate
- (void)controllerWillChangeContent:(NSFetchedResultsController *)controller {
    // The fetch controller is about to start sending change notifications, so prepare the table view for updates.
    [self.tableView beginUpdates];
}


- (void)controller:(NSFetchedResultsController *)controller didChangeObject:(id)anObject atIndexPath:(NSIndexPath *)indexPath forChangeType:(NSFetchedResultsChangeType)type newIndexPath:(NSIndexPath *)newIndexPath {
    if (!self.insertEnable ) {
        return;
    }
    UITableView *tableView = self.tableView;
    BMLog(@"newIndexPath:(ROW:%d )",newIndexPath.row);
    switch(type) {
        case NSFetchedResultsChangeInsert:
            [tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:newIndexPath] withRowAnimation:UITableViewRowAnimationFade];
            break;
    }
}

- (void)controller:(NSFetchedResultsController *)controller didChangeSection:(id )sectionInfo atIndex:(NSUInteger)sectionIndex forChangeType:(NSFetchedResultsChangeType)type {
    switch(type) {
        case NSFetchedResultsChangeInsert:
            [self.tableView insertSections:[NSIndexSet indexSetWithIndex:sectionIndex] withRowAnimation:UITableViewRowAnimationFade];
            break;
    }
}


- (void)controllerDidChangeContent:(NSFetchedResultsController *)controller {
    // The fetch controller has sent all current change notifications, so tell the table view to process all updates.
    [self.tableView endUpdates];
}
#pragma mark getter
- (NSFetchedResultsController *)fetchedResultsController {
    
    if (_fetchedResultsController != nil) {
        return _fetchedResultsController;
    }
    
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"NewsEntity"
                                              inManagedObjectContext:self.managedObjectContext];

    NSSortDescriptor *sort = [[NSSortDescriptor alloc] initWithKey:@"nid" ascending:NO];
    NSSortDescriptor *createSort = [[NSSortDescriptor alloc] initWithKey:@"create" ascending:NO];
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    [fetchRequest setEntity:entity];
    
    if (self.objectReq.type) {
        NSPredicate *predicate = [NSPredicate predicateWithFormat:@"cid == %d",self.objectReq.type];
        [fetchRequest setPredicate:predicate];
    }
    
    [fetchRequest setSortDescriptors:[NSArray arrayWithObjects:sort,createSort, nil]];
    [fetchRequest setFetchBatchSize:2000];
    
    NSFetchedResultsController *theFetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest
                                                                                                  managedObjectContext:self.managedObjectContext
                                                                                                    sectionNameKeyPath:@"cid"
                                                                                                             cacheName:@"Master"];
    self.fetchedResultsController = theFetchedResultsController;
    _fetchedResultsController.delegate = self;
    return _fetchedResultsController;
}
- (SRRefreshView*)headerCell{
    if(!_headerCell){
        _headerCell = [[SRRefreshView alloc] initWithHeight:32];
        _headerCell.delegate = self;
        _headerCell.upInset = 0;
        _headerCell.slimeMissWhenGoingBack = YES;
        _headerCell.slime.bodyColor = kPushRefreshBodyColor;
        _headerCell.slime.skinColor = kPushRefreshSkinColor;
        _headerCell.slime.lineWith = 1;
    }
    
    return _headerCell;
}
@end

